/*
 * MIT License
 *
 * Copyright (c) 2020 dybai
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>

#include "hex.h"
#include "settty.h"

int send_to_433(int fd, unsigned char val)
{
    if (write(fd, &val, 1) < 0)
    {
        return errno;
    }

    return 0;
}

int main(int argc, char *argv[])
{
    int ret = 0;
    int fd = -1;
    int value = 0;

#if 1
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s <HEX>\n", argv[0]);
        return 1;
    }

    if (hex_check(argv[1]))
    {
        fprintf(stderr, "ERROR: Illegal hexadecimal value: %s\n", argv[1]);
        return 1;
    }
#endif

    settty(PATH_TTY);

    fd = open(PATH_TTY, O_WRONLY);
    if (fd < 0)
    {
        perror("Open ttyUSB2");
        ret = errno;
        goto e_open;
    }

#if 1
    if ((ret = hex_conv_to_num(argv[1], &value)))
    {
        fprintf(stderr, "ERROR: Call conv_to_num() failed: %s\n", strerror(ret));
        ret = EINVAL;
        goto e_chk_val;
    }
    if (value < 0)
    {
        fprintf(stderr, "ERROR: The value must be greater than zero.\n");
        ret = EINVAL;
        goto e_chk_val;
    }
#endif

    // sleep(1);
    if ((ret = send_to_433(fd, (unsigned char) (value & 0xFF))))
    {
        fprintf(stderr, "ERROR: Call read_param() failed: %s\n", strerror(ret));
        goto send_to_433;
    }

    printf("Done.\n");

send_to_433:
e_chk_val:
    close(fd);
e_open:
    return ret;
}
